from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.decorators import action
from rest_framework.response import Response
from .filters import *
from .serializers import *
from django.db.models import Sum
from .handles import *
from django.db.models import Q
# Create your views here.


class GitCommitViewSet(viewsets.ModelViewSet):
    queryset = GitCommit.objects.all()
    serializer_class = GitCommitSerializer
    permission_classes = [IsAuthenticated]
    filter_class = GitCommitFilter
    pagination_class = None

    def list(self, request, *args, **kwargs):
        start = request.query_params.get('start')
        end = request.query_params.get('end')
        committer = request.query_params.get('committer')
        ref = request.query_params.get('ref')
        dim = request.query_params.get('dim', 'commit')
        if committer:
            queryset = self.queryset.filter(committer=committer)
        else:
            queryset = self.queryset
        if ref:
            queryset = queryset.filter(ref=ref)
        if dim == 'merge':
            if start and end:
                queryset = queryset.filter(
                    Q(committed_date__range=[start + ' 00:00:00', end + ' 23:59:59'], merge_date__isnull=True) | Q(
                        merge_date__range=[start + ' 00:00:00', end + ' 23:59:59']))
            elif start:
                queryset = queryset.filter(Q(committed_date__gte=start + ' 00:00:00', merge_date__isnull=True) | Q(
                    merge_date__gte=start + ' 00:00:00'))
            elif end:
                queryset = queryset.filter(Q(committed_date_lte=end + ' 23:59:59', merge_date__isnull=True) | Q(
                    merge_date_lte=end + ' 23:59:59'))
        else:
            if start and end:
                queryset = queryset.filter(committed_date__range=[start + ' 00:00:00', end + ' 23:59:59'])
            elif start:
                queryset = queryset.filter(committed_date__gte=start + ' 00:00:00')
            elif end:
                queryset = queryset.filter(committed_date_lte=end + ' 23:59:59')


        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


    @action(methods=['get'], detail=False)
    def stat(self, request, *args, **kwargs):
        datas = {}
        start = request.query_params.get('start')
        end = request.query_params.get('end')
        committer = request.query_params.get('committer')
        ref = request.query_params.get('ref')
        dim = request.query_params.get('dim', 'commit')
        maxrow = int(request.query_params.get('maxrow', 2000))
        if committer:
            queryset = self.queryset.filter(committer=committer)
        else:
            queryset = self.queryset
        if ref:
            queryset = queryset.filter(ref=ref)
        if maxrow:
            queryset = queryset.filter(additions__lte=maxrow)
        if dim == 'merge':
            if start and end:
                queryset = queryset.filter(Q(committed_date__range=[start +' 00:00:00', end + ' 23:59:59'], merge_date__isnull=True) | Q(merge_date__range=[start +' 00:00:00', end + ' 23:59:59']))
            elif start:
                queryset = queryset.filter(Q(committed_date__gte=start + ' 00:00:00', merge_date__isnull=True) | Q(merge_date__gte=start + ' 00:00:00'))
            elif end:
                queryset = queryset.filter(Q(committed_date_lte=end + ' 23:59:59', merge_date__isnull=True) | Q(merge_date_lte=end + ' 23:59:59'))
        else:
            if start and end:
                queryset = queryset.filter(committed_date__range=[start +' 00:00:00', end + ' 23:59:59'])
            elif start:
                queryset = queryset.filter(committed_date__gte=start + ' 00:00:00')
            elif end:
                queryset = queryset.filter(committed_date_lte=end + ' 23:59:59')

        for commit in queryset:
            committer = commit.committer
            total = commit.total
            additions = commit.additions
            deletions = commit.deletions
            if committer not in datas.keys():
                datas[committer] = {'committer': committer, 'total': 0, 'additions': 0, 'deletions': 0, 'committed_times': 0}
            datas[committer]['total'] += total
            datas[committer]['additions'] += additions
            datas[committer]['deletions'] += deletions
            datas[committer]['committed_times'] += 1
        return Response({'code': 20000, 'data': datas.values()})


class GitCommitDayStatViewSet(viewsets.ModelViewSet):
    queryset = GitCommitDayStat.objects.all()
    serializer_class = GitCommitDayStatSerializer
    permission_classes = [IsAuthenticated]
    filter_class = GitCommitDayStatFilter

    # @action(methods=['get'], detail=False)
    def list(self, request, *args, **kwargs):
        start = request.query_params.get('start')
        end = request.query_params.get('end')
        committer = request.query_params.get('committer')
        ref = request.query_params.get('ref')
        if committer:
            queryset = self.queryset.filter(committer=committer)
        else:
            queryset = self.queryset
        if ref:
            queryset = queryset.filter(ref=ref)
        queryset = queryset.filter(date__range=[start, end]).values('committer') \
            .order_by('committer') \
            .annotate(committed_times=Sum('committed_times'),
                      total=Sum('total'),
                      additions=Sum('additions'),
                      deletions=Sum('deletions'))

        return Response({'code': 20000, 'data': queryset})


class TapdViewSet(viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]
    @action(methods=['GET'], detail=False)
    def workspaces(self, request, *args, **kwargs):
        data = get_tapd_workspaces()
        return Response({'code': 20000, 'data': data})

    @action(methods=['GET'], detail=False)
    def stories(self, request, *args, **kwargs):
        query_params = request.query_params
        workspace_id = query_params.get('workspace_id')
        deploy_date = query_params.get('deploy_date')
        status = query_params.getlist('status', [])
        # status = ['audited']
        if not workspace_id or not deploy_date:
            return Response({'code': 10001, 'msg': '缺少参数workspace_id or deploy_date'})
        data = get_tapd_workspace_stories(workspace_id=workspace_id, deploy_date=deploy_date, status=status)
        data += get_tapd_workspace_bugs(workspace_id=workspace_id, deploy_date=deploy_date)
        return  Response({'code': 20000, 'data': data})

    @action(methods=['GET'], detail=False)
    def bugs(self, request, *args, **kwargs):
        query_params = request.query_params
        workspace_id = query_params.get('workspace_id')
        deploy_date = query_params.get('deploy_date')
        status = query_params.getlist('status', [])
        # status = ['audited']
        if not workspace_id or not deploy_date:
            return Response({'code': 10001, 'msg': '缺少参数workspace_id or deploy_date'})
        data = get_tapd_workspace_bugs(workspace_id=workspace_id, deploy_date=deploy_date)
        return Response({'code': 20000, 'data': data})

    @action(methods=['GET'], detail=False)
    def services(self, request, *args, **kwargs):
        query_params = request.query_params
        workspace_id = query_params.get('workspace_id')
        deploy_date = query_params.get('deploy_date')
        status = query_params.getlist('status', [])
        if not workspace_id or not deploy_date:
            return Response({'code': 10001, 'msg': '缺少参数workspace_id or deploy_date'})
        data = get_tapd_workspace_services(workspace_id=workspace_id, deploy_date=deploy_date, status=status)
        return Response({'code': 20000, 'data': data})
    @action(methods=['GET'], detail=False)
    def tcases(self, request, *args, **kwargs):
        query_params = request.query_params
        workspace_id = query_params.get('workspace_id')
        created = query_params.get('created')
        data = get_tapd_workspace_tcases(workspace_id=workspace_id, created=created)
        return Response({'code': 20000, 'data': data})

    @action(methods=['GET'], detail=False)
    def tplans(self, request, *args, **kwargs):
        query_params = request.query_params
        workspace_id = query_params.get('workspace_id')
        end_date = query_params.get('end_date')
        data = get_tapd_workspace_tplans(workspace_id=workspace_id, end_date=end_date)
        return Response({'code': 20000, 'data': data})

    @action(methods=['GET'], detail=False)
    def tplans_cases(self, request, *args, **kwargs):
        query_params = request.query_params
        workspace_id = query_params.get('workspace_id')
        created = query_params.get('created')
        data = stat_tapd_workspace_tplans_and_tcases(workspace_id=workspace_id, created=created)
        return Response({'code': 20000, 'data': data.values()})

class ImageDiffViewSet(viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]
    @action(methods=['GET'], detail=False)
    def kubes(self, request, *args, **kwargs):
        data = get_imagediff_kubes()
        return Response({'code': 20000, 'data': data})

    @action(methods=['GET'], detail=False)
    def info(self, request, *args, **kwargs):
        samehide = request.query_params.get('samehide', 0)
        kubes = request.query_params.getlist('kubes', [])
        datas = get_imagediff_list(kubes=kubes, samehide=samehide)

        return Response({'code': 20000, 'data': datas})

    @action(methods=['GET'], detail=False)
    def label(self, request, *args, **kwargs):
        data = get_imagediff_table_label()
        return Response({'code': 20000, 'data': data})



class ProxyRequestViewSet(viewsets.GenericViewSet):
    def list(self, request, *args, **kwargs):
        return Response({'code': 20000, 'msg': ""})
    @action(methods=['POST'], detail=False)
    def q(self, request, *args, **kwargs):
        if request.method == 'POST':
            request_url = request.data.get('request_url')
            request_method = request.data.get('request_method', 'get')
            request_headers = request.data.get('request_headers', {})
            request_body = request.data.get('request_body', {})
            response_key = request.data.get('response_key', '')
            if not request_url:
                return Response({'code': 10050, 'msg': "缺少url参数"})
            ret, data = proxy_request_handle(url=request_url, method=request_method, headers=request_headers, body=request_body, response_key=response_key)
            if ret:
                return Response({'code': 20000, 'data': data})
            else:
                return Response({'code': 10050, 'msg': data})